<?php
define('WEB_ROOT',dirname(__FILE__).'/');
define('APP_ROOT',WEB_ROOT.'app'.'/');



/**
 *核心类
 */
class core{
	private $_module = 'Default';		// 模块
	private $_controller = 'Index';		// 控制器
	private $_action = 'index';			// 方法

	/**
	 *初始化应用程序
	 */
	public function init(){
		$this->initInstall();
	}

	private function initInstall(){
		// ====== Application Directory ====== //
		self::make(APP_ROOT);
		self::make(APP_ROOT.$this->_module.'/');// Default Module Directory 
		self::make(APP_ROOT.$this->_module.'/class/');// Default Module Directory 
		self::make(APP_ROOT.$this->_module.'/tpl/');// Default Module Directory 
		self::make(APP_ROOT.$this->_module.'/model/');// Default Model Directory 

		// ====== Cache Directory ====== //
		self::make(WEB_ROOT.'cache/');

		// ====== Other Directory ====== //
		self::make(WEB_ROOT.'lib/');
		self::make(WEB_ROOT.'lib/classes');
		self::make(WEB_ROOT.'lib/function');


		$php = '<?php 
class '.$this->_controller.'{  
	public static function getInstance(){
		static $instance=null;
		if($instance===null)
			$instance = new self();
		return $instance;
	}
	private function __contrunct(){}
	private function __clone(){
		trigger_error("Clone is not allowed.", E_USER_ERROR);
	}
	public function '.$this->_action.'(){
	}   
}';
		// demo文件
		$r = self::saveFile(APP_ROOT.$this->_module.'/class/'.$this->_controller.'.php',$php);
		$r = self::saveFile(APP_ROOT.$this->_module.'/tpl/'.$this->_action.'.html','demo');

		// 锁定文件
		$r = self::saveFile(WEB_ROOT.'install.lock',1);

		echo 'Installing is Successful';

	}

	/**
	 * 创建目录
	 */
	public static function make($path){
		try{
			if(!file_exists($path)) {
				$pre_path= preg_replace("/[^\/]+\/$/i",'',$path);
				if(is_writable($pre_path)){
					mkdir($path,0755);
				}else{
					throw new Exception('\''.$pre_path.'\' don`t permit to be written!');
				}
			}
		}catch(Exception $e){
			echo $e->getMessage();exit();
		}
	}

	// 循环创建文件
	public static function rescure(){
	}

	/**
	 * 创建文件
	 */
	public static function saveFile($path,$content){
		try{
			file_put_contents($path,$content);
			return 'Your file was saved successfully'."\n";
		}catch(Exception $e){
			return 'Sorry,there was an error saving';
		}
	}
}

$core = new core();
$core->init();
